package cz.pproproj.aaservice.dldapmodule;

import org.springframework.ldap.core.*;
import org.springframework.ldap.core.support.LdapContextSource;

public class AuthenticationManager {

    private LdapContextSource ldapContextSource;
    private LdapTemplate ldapTemplate;

    public AuthenticationManager(LdapContextSource ldapContextSource) {
        this.ldapContextSource = ldapContextSource;
        ldapTemplate = new LdapTemplate(ldapContextSource);
    }

    public boolean authenticate(Credentials credentials) {

        LdapTemplate ldapTemplate = new LdapTemplate(ldapContextSource);
        return ldapTemplate.authenticate("",
                "uid=" + credentials.getUser(),
                credentials.getPassword());

    }

    public String[] findLdapGroupUsers(String groupID) {
        DistinguishedName dn = new DistinguishedName();
        dn.add("ou",groupID);
        return (String[]) ldapTemplate.lookup(dn,
                new ContextMapper() {
                    public Object mapFromContext(Object ctx) {
                        DirContextAdapter adapter  = (DirContextAdapter) ctx;
                        return adapter.getStringAttributes("uniqueMember");
                    }
                });
    }

    public boolean memberOfGroup(String user, String group) {

        String [] members = findLdapGroupUsers(group);

        for (String m : members) {
            if(m.indexOf(user) > 0) {
                return true;
            }
        }

        return false;

    }

}
